package com.ruoyi.web.utils.wechat;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;

/**
 * 微信获取AccessToken类
 */
public class AccessToken {
    private final static String URL_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    private static String accessToken;
    private static long lastUpdateTime = -1;
    private static void update() {
        try {
            //当前使用天蛙小程序appid、secret
            String url = URL_TOKEN + "appid=" + "wxd602e0793295cc28" + "&secret=" + "7ec0b59e73b75b7388bd0323f1d29955";
            String body = HttpRequest.get(url).execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            accessToken = jsonObject.getString("access_token");
            lastUpdateTime = System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getAccessToken() {
        long cur = System.currentTimeMillis();
        if (lastUpdateTime == -1 || cur - lastUpdateTime > 3600000) {
            update();
        }
        return accessToken;
    }
}
